import java.io.*;
import java.util.*;

public class Anagrams {
    public Map<String, Set<String>> readFromFile(String sourcePath) throws IOException {
        if (sourcePath == null)
            throw new NullPointerException();

        Map<String, Set<String>> result = new HashMap<String, Set<String>>();

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(new File(sourcePath)), "UTF-8"));

        String nextLine;
        StringParser sp = new StringParser();
        try {
            while ((nextLine = reader.readLine()) != null) {
                Set<String> words = sp.parse(nextLine);
                for (String word : words) {
                    if (!result.containsKey(sp.toLowerCaseSort(word))) {
                        result.put(sp.toLowerCaseSort(word), new HashSet<String>());
                        result.get(sp.toLowerCaseSort(word)).add(word);
                    } else {
                        result.get(sp.toLowerCaseSort(word)).add(word);
                    }
                }
            }
        } finally {
            reader.close();
        }
        return result;
    }

    public void writeAnagramsToFile(Map<String, Set<String>> map, String destinationPath)
            throws IOException {
        if (map == null || map.isEmpty()
                || destinationPath == null || destinationPath.isEmpty())
            return;

        Set<String> keySet = map.keySet();
        PrintWriter out = new PrintWriter(new File(destinationPath), "UTF-8");
        try {
            for (String key : keySet) {
                if (map.get(key).size() > 1) {
                    for (String word : map.get(key)) {
                        if (word != null) {
                            out.write(word + ", ");
                        }
                    }
                    out.println();
                }
            }
        } finally {
            out.close();
        }
    }
}
